package com.ruoyi.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-10-21 09:24
 **/
@Configuration
public class GatewayConfig implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        System.out.println("访问路径是："+url);

        String[] SuccessUrl = new String[]{"/user/login"};
        for (String s : SuccessUrl){
            if(url.equals(s)){
                System.out.println("放行路径："+s);
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("token");

        if(StringUtils.isEmpty(token)){
            System.out.println("token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        boolean signed = Jwts.parser().isSigned(token);
        if(!signed){
            System.out.println("token无效");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("userId", Integer.class);

        Boolean expire = redisTemplate.expire("token:" + userId, 30, TimeUnit.MINUTES);
        if(expire){
            System.out.println("token有效时间刷新");
            return chain.filter(exchange);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
